<template>
  <div class="banner">
    <div class="box" v-if="banners.length !== 0">
      <div class="container"
      :style="{width: containerW, transform: transform}"
      @touchstart="touchStart"
      @touchmove="touchMove"
      @touchend="touchEnd"
      ref="container">
        <div class="item">
          <img :src="banners[banners.length-1].pic">
        </div>
        <div
        class="item"
        v-for="(item, index) in banners"
        :key="index"
        ref="item">
          <img :src="item.pic">
        </div>
        <div class="item">
          <img :src="banners[0].pic">
        </div>
      </div>
    </div>
    <div class="banner-bottom">
      <span
      :class="(index == currIndex - 1) || 
      (currIndex == 0 && index == banners.length-1) ? 
      'pot potActive' : 
      'pot'"
      v-for="(item, index) in banners"
      :key="index"
      @click="clickDot(index)"></span>
    </div>
  </div>
</template>

<script>
  export default {
    name: "Banner",
    data(){
      return {
        banners: [],
        currIndex: 1,
        containerW: 0,
        timer: '',
        flag: true,
        transform: '',
        startX: 0,
        moveX: 0
      };
    },
    methods: {
      getBannerImages(){  //获取轮播图数据
        this.$axios.get('/api/banner/?type=1')
          .then(res => {
            this.banners = res.data.banners;
            console.log(this.banners);
            this.autoMove();
          })
          .catch(err => console.log(err));
      },
      autoMove(){  //自动开始轮播
        this.$nextTick(() => {
          let container = this.$refs.container;
          console.log(this.$refs.item[0].offsetWidth);
          let itemW = this.$refs.item[0].offsetWidth;
          // 由于offsetWidth获取到的宽度为整数，而实际上 vw/%/vh 得到的px单位宽度并不是整数
          // 所以要重新动态给所有元素赋予这个值的宽度，避免精度误差
          // console.log(this.$refs.container.childNodes); //所以子节点
          this.$refs.container.childNodes.forEach((item) => {
            item.style.width = itemW + 'px';
          });
          this.transform = `translateX(${-(itemW) * (this.currIndex)}px)`;
          // this.transform = `translateX(${-itemW}px)`;
          this.containerW = itemW * (this.banners.length + 2) + 'px';
          this.timer = setInterval(() => {
            // console.log(this.currIndex);
            this.currIndex++;
            container.style.transition = 'all 1s';
            this.transform = `translateX(${-(itemW) * (this.currIndex)}px)`;
          }, 3000);
          //过度执行结束后 会触发 transitionend 事件
          container.addEventListener('transitionend', () => {
              // console.log(this.currIndex);
              if (this.currIndex > this.banners.length) {
                  this.currIndex = 1;
                  //取消过度
                  container.style.transition = 'none';
                  this.transform = `translateX(${-(itemW) * (this.currIndex)}px)`;
              }else if(this.currIndex <= 0){
                  this.currIndex = this.banners.length;
                  var translatex = -this.currIndex * itemW;
                  container.style.transition = 'none';
                  this.transform = 'translateX('+translatex+'px)';
              }
              //为节流阀设置为true
              this.flag = true;
          });


        });
      },
      clickDot(index){  //点击小点
        let itemW = this.$refs.item[0].offsetWidth;
        if(this.currIndex === (index + 1)){return;}
        this.currIndex = index + 1;
        this.transform = `translateX(${-this.currIndex * itemW}px)`;
      },
      touchStart(e){
        this.$nextTick(() => {
          this.startX = e.targetTouches[0].pageX;
          // this.containerX = this.$refs.container.offsetLeft;
          //清除定时器
          clearInterval(this.timer);
          this.timer = null;
        });
        
      },
      touchMove(e){
        e.preventDefault();
        this.$nextTick(() => {
          if (this.flag) {
              this.moveX = e.targetTouches[0].pageX - this.startX;
              let translatex = -this.currIndex * this.$refs.item[0].offsetWidth + this.moveX;
              //取消过度
              this.$refs.container.style.transition = 'none';
              this.transform = 'translatex(' + translatex + 'px)';
          }
        });

      },
      touchEnd(e){
        this.$nextTick(() => {
          if (this.flag) {
            //将节流阀设置为false
            this.flag = false;
            if (Math.abs(this.moveX) >= 50) {
                if (this.moveX > 0) {
                    this.currIndex--;
                } else {
                    this.currIndex++;
                }
                let translatex = -this.currIndex * this.$refs.item[0].offsetWidth;
                //添加过度效果
                this.$refs.container.style.transition = 'all 1s';
                this.transform = 'translatex(' + translatex + 'px)';
            } else {
                let translatex = -this.currIndex * this.$refs.item[0].offsetWidth;
                //添加过度效果
                this.$refs.container.style.transition = 'all 1s';
                this.transform = 'Translatex(' + translatex + 'px)'
            }
            //清除定时器
            clearInterval(this.timer);
            //重启轮播
            this.timer = setInterval(() => {
                this.currIndex++;
                let translate = -this.currIndex * this.$refs.item[0].offsetWidth;
                //设置元素的移动在2s内完成 给元素添加过度
                this.$refs.container.style.transition = 'all 1s';
                this.transform = 'translateX(' + translate + 'px)';
            }, 3000);

          }
        });

      }



    },
    mounted(){
      this.getBannerImages();
    }
  }
</script>

<style scoped>
  .banner{
    width: 100vw;
    height: 35vw;
    margin-top: 10px;
    position: relative;
  }
  .box{
    width: 90vw;
    height: 100%;
    margin: 0 auto;
    border-radius: 6px;
    position: relative;
    overflow: hidden;
  }
  .container{
    height: 35vw;
  }
  .container .item{
    float: left;
    width: 90vw;
    height: 35vw;
    font-size: 0;
    position: relative;
  }
  .container:last-child::after{
    content: "";
    float: none;
  }
  .container .item img{
    width: 100%;
    height: 100%;
  }

  .banner-bottom{
    width: 100%;
    height: 20px;
    display: flex;
    justify-content: center;
    align-items: center;
    position: absolute;
    left: 0;
    bottom: 2%;
  }
  .pot{
    width: 10px;
    height: 10px;
    margin-left: 4px;
    margin-right: 4px;
    border-radius: 50%;
    background: rgba(255, 255, 255, 0.4);
  }
  .potActive{
    background: #ffffff;
  }
</style>